import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description: 删除博客的后端代码
 * User: 86187
 * Date: 2022-11-28
 * Time: 0:21
 */
@WebServlet("/blog_delete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 判定用户登陆状态.
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!不能删除博客!");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录!不能删除博客!");
            return;
        }
        // 2. 获取到 blogID
        String blogId = req.getParameter("blogId");
        if (blogId == null) {
            // blogId 不存在, 也无法删除.
            // resp.setStatus(404);
            // resp.setContentType("text/html; charset=utf8");
            // resp.getWriter().write("当前访问的资源有误!");

            // 自己改的
            resp.setStatus(302);
            resp.sendRedirect("delete_error.html");

            return;
        }
        // 3. 查询这个 blogId 对应的 Blog 对象
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if (blog == null) {
            // 博客不存在
            // resp.setStatus(404);
            // resp.setContentType("text/html; charset=utf8");
            // resp.getWriter().write("要删除的博客不存在! blogId = " + blogId);

            // 自己改的
            resp.setStatus(302);
            resp.sendRedirect("delete_error.html");

            return;
        }
        // 4. 判定登录用户是否就是文章作者
        if (blog.getUserId() != user.getUserId()) {
//            resp.setStatus(403);
//            resp.setContentType("text/html; charset=utf8");
//            resp.getWriter().write("您无权限删除别人的博客!");

            // 自己改的
            resp.setStatus(302);
            resp.sendRedirect("delete_error.html");

            return;
        }
        // 5. 真正执行删除操作
        blogDao.delete(Integer.parseInt(blogId));
        // 6. 返回 302 重定向.
        resp.setStatus(302);
        resp.sendRedirect("delete_success.html");
    }
}
